import React, { useEffect, useState } from 'react';
import './Settings.css';
import ShortcutInput from './ShortcutInput';

interface SettingsProps {
  onClose: () => void;
}

const Settings: React.FC<SettingsProps> = ({ onClose }) => {
  const [currentSavePath, setCurrentSavePath] = useState<string>('');
  const [isLoading, setIsLoading] = useState(false);
  const [currentShortcut, setCurrentShortcut] = useState<string>('');
  const [isShortcutLoading, setIsShortcutLoading] = useState(false);

  useEffect(() => {
    // 获取当前保存路径和快捷键
    const loadCurrentSettings = async () => {
      try {
        const [path, shortcut] = await Promise.all([
          window.electronAPI.getSaveFolder(),
          window.electronAPI.getShortcut()
        ]);
        setCurrentSavePath(path);
        setCurrentShortcut(shortcut);
      } catch (error) {
        console.error('获取设置失败:', error);
      }
    };

    loadCurrentSettings();

    // ESC 键关闭设置
    const handleKeyPress = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose();
      }
    };

    document.addEventListener('keydown', handleKeyPress);
    return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, [onClose]);

  const handleSelectFolder = async () => {
    try {
      setIsLoading(true);
      const selectedPath = await window.electronAPI.selectSaveFolder();
      
      if (selectedPath) {
        setCurrentSavePath(selectedPath);
        alert(`截图保存路径已更新为:\n${selectedPath}`);
      }
    } catch (error) {
      console.error('选择文件夹失败:', error);
      alert('选择文件夹失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  const handleResetToDefault = async () => {
    try {
      setIsLoading(true);
      const defaultPath = await window.electronAPI.resetSaveFolder();
      setCurrentSavePath(defaultPath);
      alert(`截图保存路径已重置为默认路径:\n${defaultPath}`);
    } catch (error) {
      console.error('重置路径失败:', error);
      alert('重置路径失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  const handleOpenFolder = () => {
    // 在操作系统中打开文件夹
    if (window.electronAPI.platform === 'darwin') {
      // macOS
      window.open(`file://${currentSavePath}`);
    } else if (window.electronAPI.platform === 'win32') {
      // Windows
      window.open(`file://${currentSavePath}`);
    } else {
      // Linux 和其他
      window.open(`file://${currentSavePath}`);
    }
  };

  const handleShortcutChange = async (shortcut: string) => {
    if (!shortcut.trim()) {
      setCurrentShortcut('');
      return;
    }

    try {
      setIsShortcutLoading(true);
      const result = await window.electronAPI.setShortcut(shortcut);
      
      if (result.success) {
        setCurrentShortcut(shortcut);
        alert(`快捷键设置成功: ${shortcut}`);
      } else {
        alert(`快捷键设置失败: ${result.message}`);
        // 恢复到之前的快捷键
        const currentShortcut = await window.electronAPI.getShortcut();
        setCurrentShortcut(currentShortcut);
      }
    } catch (error) {
      console.error('设置快捷键失败:', error);
      alert('设置快捷键失败，请重试');
    } finally {
      setIsShortcutLoading(false);
    }
  };

  const handleValidateShortcut = async (shortcut: string) => {
    try {
      return await window.electronAPI.validateShortcut(shortcut);
    } catch (error) {
      console.error('验证快捷键失败:', error);
      return { valid: false, message: '验证失败' };
    }
  };

  const handleResetShortcut = async () => {
    try {
      setIsShortcutLoading(true);
      const result = await window.electronAPI.resetShortcut();
      
      setCurrentShortcut(result.shortcut);
      alert(result.message);
    } catch (error) {
      console.error('重置快捷键失败:', error);
      alert('重置快捷键失败，请重试');
    } finally {
      setIsShortcutLoading(false);
    }
  };

  return (
    <div className="settings-overlay">
      <div className="settings-modal">
        <div className="settings-header">
          <h2>截图设置</h2>
          <button className="close-btn" onClick={onClose}>
            ✕
          </button>
        </div>

        <div className="settings-content">
          <div className="setting-section">
            <h3>快捷键设置</h3>
            <div className="shortcut-setting">
              <div className="setting-item">
                <label className="setting-label">截图快捷键</label>
                <ShortcutInput
                  value={currentShortcut}
                  onChange={handleShortcutChange}
                  onValidate={handleValidateShortcut}
                  disabled={isShortcutLoading}
                  placeholder="点击录制快捷键..."
                />
              </div>
              
              <div className="shortcut-actions">
                <button 
                  className="btn-secondary"
                  onClick={handleResetShortcut}
                  disabled={isShortcutLoading}
                >
                  {isShortcutLoading ? '重置中...' : '恢复默认'}
                </button>
              </div>
              
              <div className="shortcut-tips">
                <div className="tip-item">
                  <span className="tip-icon">💡</span>
                  <span>推荐使用 Ctrl/Cmd + Shift + 字母 的组合</span>
                </div>
                <div className="tip-item">
                  <span className="tip-icon">⚠️</span>
                  <span>避免与系统或其他应用的快捷键冲突</span>
                </div>
              </div>
            </div>
          </div>

          <div className="setting-section">
            <h3>保存位置</h3>
            <div className="save-path-info">
              <div className="current-path">
                <span className="path-label">当前路径:</span>
                <span className="path-value" title={currentSavePath}>
                  {currentSavePath}
                </span>
              </div>
              
              <div className="path-actions">
                <button 
                  className="btn-primary"
                  onClick={handleSelectFolder}
                  disabled={isLoading}
                >
                  {isLoading ? '选择中...' : '选择文件夹'}
                </button>
                
                <button 
                  className="btn-secondary"
                  onClick={handleOpenFolder}
                  disabled={isLoading}
                >
                  打开文件夹
                </button>
                
                <button 
                  className="btn-secondary"
                  onClick={handleResetToDefault}
                  disabled={isLoading}
                >
                  恢复默认
                </button>
              </div>
            </div>
          </div>

          <div className="setting-section">
            <h3>说明</h3>
            <div className="setting-description">
              <ul>
                <li>📁 截图将保存到指定的文件夹中</li>
                <li>📋 截图同时会自动复制到剪贴板</li>
                <li>🔄 可以随时更改保存位置</li>
                <li>⚡ 默认保存位置是系统下载文件夹</li>
                <li>⌨️ 自定义快捷键，提高使用效率</li>
              </ul>
            </div>
          </div>
        </div>

        <div className="settings-footer">
          <button className="btn-secondary" onClick={onClose}>
            关闭
          </button>
        </div>
      </div>
    </div>
  );
};

export default Settings;